package com.archive.manage.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;

import com.archive.common.constant.HttpStatus;
import com.archive.common.constant.Operation_type;
import com.archive.common.constant.RoleConstant;
import com.archive.common.core.domain.entity.SysUser;
import com.archive.common.core.domain.model.LoginUser;
import com.archive.common.utils.SecurityUtils;
import com.archive.common.utils.bean.BeanUtils;
import com.archive.framework.web.service.SysPermissionService;
import com.archive.manage.domain.Resume;
import com.archive.manage.domain.StuClassInfo;
import com.archive.manage.domain.Vo.StuArchiveVo;
import com.archive.manage.service.IArchiveLogService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.archive.common.annotation.Log;
import com.archive.common.core.controller.BaseController;
import com.archive.common.core.domain.AjaxResult;
import com.archive.common.enums.BusinessType;
import com.archive.manage.domain.StuArchive;
import com.archive.manage.service.IStuArchiveService;
import com.archive.common.utils.poi.ExcelUtil;
import com.archive.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 学生档案管理Controller
 * 
 * @author marioduan
 * @date 2025-04-02
 */
@RestController
@RequestMapping("/manage/archive")
public class StuArchiveController extends BaseController
{
    @Autowired
    private IStuArchiveService stuArchiveService;

    @Autowired
    private IArchiveLogService archiveLogService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 查询学生档案管理列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:list')")
    @GetMapping("/list")
    public TableDataInfo list(StuArchive stuArchive)
    {
        startPage();
        //获取登录者的角色
        Set<String> rolePermission = getLoginUserRoles();
        //判断登录者的角色,如果是学生则只显示本学生的信息
        if(rolePermission.contains(RoleConstant.STUDENT)){
            StuArchive student = stuArchiveService.selectStuArchiveByStudentId(SecurityUtils.getLoginUser().getUsername());
            List<StuArchiveVo> list = new ArrayList<>();
            if(student!=null)
                list.add(copyStuArchiveToStuArchiveVo(student));
            return getDataTable(list);
        }

        List<StuArchive> list = stuArchiveService.selectStuArchiveList(stuArchive);

        // 先获取分页信息
        TableDataInfo tableInfo = getDataTable(list);

        // 再处理数据转换
        List<StuArchive> pageList = (List<StuArchive>) tableInfo.getRows();
        List<StuArchiveVo> result = new ArrayList<>();
        for (StuArchive item : pageList)
            result.add(copyStuArchiveToStuArchiveVo(item));

        // 更新结果
        tableInfo.setRows(result);
        return tableInfo;
    }

    /**
     * 导出学生档案管理列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:export')")
    @Log(title = "学生档案管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StuArchive stuArchive) throws Exception {
        List<StuArchive> list = stuArchiveService.selectStuArchiveList(stuArchive);
        ExcelUtil<StuArchive> util = new ExcelUtil<StuArchive>(StuArchive.class);
        util.exportExcel(response, list, "学生档案管理数据");
        //util.exportEasyExcel(response, list, "学生档案管理数据");
        List<String> studentIds = new ArrayList<>();
        for (StuArchive stu : list) {
            studentIds.add(stu.getStudentId());
        }
        archiveLogService.batchExportArchiveLog(studentIds.toArray(new String[studentIds.size()]),Operation_type.EXPORT);
    }
    /**
     * 批量导入学生档案列表
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:add')")
    @Log(title = "学生档案管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult excelImport(MultipartFile file) throws Exception {
        ExcelUtil<StuArchive> StuArchiveExcelUtil = new ExcelUtil<>(StuArchive.class);
        List<StuArchive> stuArchiveList = StuArchiveExcelUtil.importEasyExcel(file.getInputStream());
        if(stuArchiveList.isEmpty())
            return error(file.getName()+"为空");
        if(!chickOnlyArchive(stuArchiveList))
            return new AjaxResult(500,"每名学生只能添加一个档案");
        return success(stuArchiveService.batchInsertStuArchive(stuArchiveList));
    }

    /**
     * 获取学生档案管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:query')")
    @GetMapping(value = "/{studentId}")
    public AjaxResult getInfo(@PathVariable("studentId") String studentId)
    {
        StuArchive stuArchive = stuArchiveService.selectStuArchiveByStudentId(studentId);
        if(stuArchive!=null)
            return success(copyStuArchiveToStuArchiveVo(stuArchive));
        else return error("未找到"+studentId+"学号");
    }

    /**
     * 新增学生档案管理
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:add')")
    @Log(title = "学生档案管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StuArchiveVo stuArchiveVo) throws Exception {
        if(!chickOnlyArchive(null))
            return new AjaxResult(500,"每名学生只能添加一个档案");
        return toAjax(stuArchiveService.insertStuArchive(stuArchiveVo));
    }

    /**
     * 修改学生档案管理
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:edit')")
    @Log(title = "学生档案管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StuArchiveVo stuArchiveVo) throws Exception
    {
        return toAjax(stuArchiveService.updateStuArchive(stuArchiveVo));
    }

    /**
     * 删除学生档案管理
     */
    @PreAuthorize("@ss.hasPermi('manage:archive:remove')")
    @Log(title = "学生档案管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{studentIds}")
    public AjaxResult remove(@PathVariable String[] studentIds) throws Exception {
        return toAjax(stuArchiveService.deleteStuArchiveByStudentIds(studentIds));
    }

    /**
     * 获取登录用户的角色
     * @return 角色集合
     */
    private Set<String> getLoginUserRoles(){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return permissionService.getRolePermission(loginUser.getUser());
    }

    /**
     * 将StuArchive中的班级信息和简历信息拷贝到StuArchiveVo里,以便在前端展示
     * @param student
     * @return
     */
    private StuArchiveVo copyStuArchiveToStuArchiveVo(StuArchive student){
        String[] ignoreProperties = {"createTime", "updateTime","createBy","updateBy","remark"};
        StuArchiveVo stuArchiveVo = new StuArchiveVo();
        BeanUtils.copyProperties(student, stuArchiveVo);
        if (!student.getStuClassInfoList().isEmpty()) {
            StuClassInfo stuClassInfo = student.getStuClassInfoList().get(0);
            BeanUtils.copyProperties(stuClassInfo, stuArchiveVo, ignoreProperties);
            student.getStuClassInfoList().clear();
        }
        if (!student.getResumeInfoList().isEmpty()) {
            Resume resume = student.getResumeInfoList().get(0);
            BeanUtils.copyProperties(resume, stuArchiveVo, ignoreProperties);
            stuArchiveVo.setResumeId(resume.getId());
            student.getResumeInfoList().clear();
        }
        return stuArchiveVo;
    }

    /**
     * 该方法的核心目的是确保每个学生只能添加一个档案。
     * 管理员用户可以不受限制。
     * 学生用户不能重复添加自己的档案。
     * 非学生用户（如教师或其他角色）在导入多个档案时，需要确保数量不超过 1，否则拒绝操作。
     * @param list
     * @return
     */
    private Boolean chickOnlyArchive(List<?> list){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        if(user.isAdmin())
            return true;
        String username = user.getUserName();
        StuArchive stuArchive = stuArchiveService.selectStuArchiveByStudentId(username);
        Set<String> loginUserRoles = getLoginUserRoles();
        if(list.isEmpty()&&stuArchive!=null&&loginUserRoles.contains(RoleConstant.STUDENT))
            return false;
        if(!list.isEmpty()&&loginUserRoles.contains(RoleConstant.STUDENT))
            return list.size() <= 1 && stuArchive == null;
        return true;
    }
}
